package com.example.demorabbitmq;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liyh <levart@163.com>
 * @version 20210729
 */
@Configuration
public class MqConfig {

    /**
     * 交换机
     */
    public static final String EXCHANGE = "exchange1";
    /**
     * 路由key
     */
    public static final String ROUTER_KEY = "routerKey";
    /**
     * 队列
     */
    public static final String QUEUE = "queue";


    @Bean
    public DirectExchange demoExchange() {
        DirectExchange directExchange = new DirectExchange(EXCHANGE);
        return directExchange;
    }

    @Bean
    public Queue demoQueue() {
        Map<String, Object> arguments = new HashMap<>();
        Queue queue = new Queue(QUEUE, true, false, false, arguments);
        return queue;
    }

    @Bean
    public Binding bindingQueueToExchange() {
        Binding binding = BindingBuilder.bind(demoQueue()).to(demoExchange()).with(ROUTER_KEY);
        return binding;
    }


    /**
     * 消费队列中的数据
     * @param message
     * @param channel
     */
    @RabbitListener(queues = QUEUE)
    public void listen2(Message message, Channel channel) {
        System.out.println("receive timeout message ====");
        String body = new String(message.getBody());
        System.out.println(body);

        MessageVO messageVO = JSON.parseObject(body, MessageVO.class);
        messageVO.setSendCount(messageVO.getSendCount() + 1);
        try {
            // 确认消息已消费
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

